package me.zhengjie.modules.system.rest;

import me.zhengjie.base.AjaxResult;
import me.zhengjie.config.FileProperties;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.utils.FileUtil;
import me.zhengjie.utils.StringUtils;
import me.zhengjie.utils.file.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.HashMap;

/**
 * 通用请求处理
 *
 * @author ruoyi
 */
@Controller
public class CommonController {

//    @Autowired
//    private ServerConfig serverConfig;

    @Value("${site.url}")
    private String siteUrl;

    @Autowired
    private FileProperties properties;

    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    /**
     * 文件上传路径
     */
    public static final String UPLOAD_PATH = "/file/";
    public static final String DOWNLOAD_PATH = "/download/";

    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     * @param delete   是否删除
     */
    public void _fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request) {
        try {
            if (!FileUtils.isValidFilename(fileName)) {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 " , fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = DOWNLOAD_PATH + fileName;

            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition" ,
                    "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, realFileName));
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete) {
                FileUtils.deleteFile(filePath);
            }
        } catch (Exception e) {
            log.error("下载文件失败" , e);
        }
    }

    /**
     * 通用上传请求
     */
    public AjaxResult _uploadFile(MultipartFile multipartFile,String flag){
        try {
            // 文件大小验证
            FileUtil.checkSize(properties.getMaxSize(), multipartFile.getSize());
            // 验证文件上传的格式
            String image = "gif jpg png jpeg";
            if(flag == "img"){
            }else if(flag == "file"){
                image = "mp3 mp4 mid mpg avi zip rar doc docx xls xlsx amr";
            }
            String fileType = FileUtil.getExtensionName(multipartFile.getOriginalFilename());
            if(fileType != null && !image.contains(fileType)){
                throw new BadRequestException("文件格式错误！, 仅支持 " + image +" 格式");
            }
            File file = FileUtil.upload(multipartFile, properties.getPath().getPath());

            //截取取随机目录
            String imgLeft = file.getParent();
            String dayStr = imgLeft.replace(properties.getPath().getPath(),"")+"/";

//            String url = serverConfig.getUrl() + UPLOAD_PATH +dayStr+file.getName();
            String url =  siteUrl + UPLOAD_PATH +dayStr+file.getName();
            HashMap tmp = new HashMap();
            tmp.put("fileName" , file.getName());
            tmp.put("url" , url);
            return AjaxResult.success(tmp);
        } catch (Exception e) {
            return AjaxResult.error("上传异常："+e.getMessage());
        }
    }
}
